//
//  TaskListViewController.m
//  OAProject
//
//  Created by yhj on 2017/3/8.
//  Copyright © 2017年 cdnunion. All rights reserved.
//  任务列表主界面

#import "TaskListViewController.h"
#import "TaskListTableViewCell.h"
#import "AddTaskViewController.h"
#import "TaskListModel.h"
#import "TaskDetailViewController.h"
#import "DropDownMenu.h"
#import "EditTaskViewController.h"
#import "AddTaskProcessViewController.h"
#import "SelectContactListViewController.h"
#import "UpdateTaskLogViewController.h"

static NSString *TaskListTableViewCellIdentifier=@"tableViewCellIdentifier";
@interface TaskListViewController ()<UITableViewDataSource,UITableViewDelegate,TaskListTableViewCellDelegate,SelectContactListViewControllerDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)DropDownMenu *dropDownMenu;

@property(nonatomic,strong)NSArray *titles;

@property(nonatomic,strong)NSMutableArray *taskListArr;

@property(nonatomic,assign)BOOL isSelect;

@property(nonatomic,strong)NSString *userID;

@property(nonatomic,strong)NSString *createrID;

@property(nonatomic,strong)NSString *taskStatus;

// 当前页
@property (nonatomic,assign)int currentPage;

@end

@implementation TaskListViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.taskListArr=[NSMutableArray array];

    [self addHeader];

    [self addFooter];

}

-(void)addHeader
{
    WEAKSELF;
    self.tableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage=1;

        [self.taskListArr removeAllObjects];

        [weakSelf GetTaskListData];
    }];
    [self.tableView.mj_header beginRefreshing];
}

-(void)addFooter
{
    WEAKSELF;
    MJRefreshAutoNormalFooter *footer=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage += 1;
        [weakSelf GetTaskListData];
    }];
    [footer setTitle:@"我是有底线的" forState:MJRefreshStateNoMoreData];
    footer.automaticallyHidden=YES;
    self.tableView.mj_footer=footer;
}


// delegate
-(void)SuccessSelectContact
{
    [self addHeader];
    [self addFooter];
}

// 编辑任务
-(void)editTaskWithTaskListModel:(TaskListModel *)model cell:(TaskListTableViewCell *)cell
{
    __block BOOL isEdit=NO;
    [model.opts enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         if ([obj isEqualToString:@"edit"])
         {
             isEdit=YES;
             *stop=YES;
         }
     }];

    if (isEdit)
    {
        EditTaskViewController *vc=[EditTaskViewController new];
        vc.model=model;
        [self.navigationController pushViewController:vc animated:NO];
    }
    else
    {
        [self.view makeToast:@"没权限操作" duration:.5 position:CSToastPositionCenter];
    }
}

// 取消任务delegate
-(void)deleteTaskWithTaskListModel:(TaskListModel *)model cell:(TaskListTableViewCell *)cell
{
    __block BOOL isCancel=NO;
    [model.opts enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         if ([obj isEqualToString:@"cancel"])
         {
             isCancel=YES;
             *stop=YES;
         }
     }];

    if (isCancel)
    {
        UIAlertView *alert=[UIAlertView alertViewWithTitle:@"提示" message:@"你确定要终止此任务吗？" cancelButtonTitle:@"取消" didDismissBlock:^(UIAlertView *alertView,NSInteger buttonIndex) {

            if (buttonIndex==0)
            {
                [API CancelTaskWithTaskID:model.taskID success:^(id res) {

                    if ([res[@"rt"] isEqual:@(1)])
                    {
                        [self addHeader];
                        [self addFooter];
                    }
                    else
                    {
                        [self.view makeToast:res[@"error"] duration:1 position:CSToastPositionCenter];
                    }
                    
                } failure:^(NSInteger stateCode) {

                }];
            }
        } otherButtonTitles:@"确定", nil];
        [alert show];
    }
    else
    {
      [self.view makeToast:@"没权限操作" duration:.5 position:CSToastPositionCenter];
    }
}


-(void)viewDidLoad
{
    [super viewDidLoad];

    // 菜单是否选择
    _isSelect=NO;

    self.automaticallyAdjustsScrollViewInsets=NO;

    self.view.backgroundColor=MAIN_BACK_COLOR;

    [self.view addSubview:self.tableView];

    // 初始化菜单
    [self initMenuData];

    [self addTask];

}

-(void)GetTaskListData
{
    WEAKSELF;
    if (_isSelect==NO)
    {
        [API GetTaskListWithProjectID:@"" createrID:@"" userID:@"" targetType:@"" priority:@"" status:@"not_started" stepStatus:@"" per_page:KCountNumber page_num:[NSString stringWithFormat:@"%d",self.currentPage] success:^(id res) {

            [weakSelf endRefresh:self.tableView array:self.taskListArr];

            if ([res[@"rt"] isEqual:@(1)])
            {
                NSArray *array=res[@"rows"];
                if (array.count>0)
                {
                    for (NSDictionary *dic in array)
                    {
                        TaskListModel *model=[TaskListModel yy_modelWithDictionary:dic];
                        [weakSelf.taskListArr addObject:model];
                    }
                }
                else
                {
                     [self.view makeToast:@"暂无数据" duration:1 position:CSToastPositionCenter];
                }

                if (self.currentPage<[res[@"page"][@"pages"] integerValue])
                {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
                else
                {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            else
            {
                 [self.view makeToast:res[@"error"] duration:1 position:CSToastPositionCenter];
            }
            [weakSelf.tableView reloadData];
            
        } failure:^(NSInteger stateCode) {
            
            [weakSelf requestFail:self.tableView array:self.taskListArr];
            
        }];
    }
    else
    {
        WEAKSELF;
        [API GetTaskListWithProjectID:@"" createrID:self.createrID userID:self.userID targetType:@"" priority:@"" status:self.taskStatus stepStatus:@"" per_page:KCountNumber page_num:[NSString stringWithFormat:@"%d",self.currentPage] success:^(id res) {

            [weakSelf endRefresh:self.tableView array:self.taskListArr];

            if ([res[@"rt"] isEqual:@(1)])
            {
                NSArray *array=res[@"rows"];
                if (array.count>0)
                {
                    for (NSDictionary *dic in array)
                    {
                        TaskListModel *model=[TaskListModel yy_modelWithDictionary:dic];
                        [weakSelf.taskListArr addObject:model];
                    }
                }
                else
                {
                    [self.view makeToast:@"暂无数据" duration:1 position:CSToastPositionCenter];
                }

                if (self.currentPage<[res[@"page"][@"pages"] integerValue])
                {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
                else
                {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            else
            {
                [self.view makeToast:res[@"error"] duration:1 position:CSToastPositionCenter];
            }

            [weakSelf.tableView reloadData];
            
        } failure:^(NSInteger stateCode) {
            
            [weakSelf requestFail:self.tableView array:self.taskListArr];

        }];
    }
}

#pragma mark 上下拉刷新
- (void)endRefresh:(UITableView *)tableView array:(NSMutableArray *)array
{
    if ([tableView.mj_header isRefreshing])
    {
        [array removeAllObjects];
        [tableView.mj_header endRefreshing];
    }
    if ([tableView.mj_footer isRefreshing])
    {
        [tableView.mj_footer endRefreshing];
    }
}

// 收到请求失败的通知
- (void)requestFail:(UITableView *)tableView array:(NSMutableArray *)array
{
    if ([tableView.mj_header isRefreshing])
    {
        [tableView.mj_header endRefreshing];
    }
    if ([tableView.mj_footer isRefreshing])
    {
        [tableView.mj_footer endRefreshing];
    }
    [array removeAllObjects];
    [tableView reloadData];
}


-(void)addTask
{
    UIButton *addBtn=[AppUI createButtonWithSupeView:self.view andWithNormalImage:[UIImage imageNamed:@"add"] andWithSelectImage:[UIImage imageNamed:@"add"] andWithBtnAction:^{

        // 跳转到 项目添加 界面
        AddTaskViewController *vc=[AddTaskViewController new];
        [self.navigationController pushViewController:vc animated:NO];
    }];
    [self.view addSubview:addBtn];
    addBtn.frame=CGRectMake(APPW-kmargin*8,APPH-kmargin*10,kmargin*6,kmargin*6);
}

-(void)initMenuData
{
    DTKDropdownItem *item1=[DTKDropdownItem itemWithTitle:@"未开始的任务" callBack:^(NSUInteger index, id info) {
        self.taskStatus=@"not_started";
        self.userID=@"";
        self.createrID=@"";
        self.isSelect=YES;
        [self addHeader];
        [self addFooter];
    }];

    DTKDropdownItem *item2=[DTKDropdownItem itemWithTitle:@"进行中的任务" callBack:^(NSUInteger index, id info) {
        self.taskStatus=@"doing";
        self.userID=@"";
        self.createrID=@"";
        self.isSelect=YES;
        [self addHeader];
        [self addFooter];
    }];


    DTKDropdownItem *item3=[DTKDropdownItem itemWithTitle:@"参与的任务" callBack:^(NSUInteger index, id info) {
        self.userID=@"-1";
        self.createrID=@"";
        self.taskStatus=@"";
        self.isSelect=YES;
        [self addHeader];
        [self addFooter];
    }];


    DTKDropdownItem *item4=[DTKDropdownItem itemWithTitle:@"完成的任务" callBack:^(NSUInteger index, id info) {
        self.taskStatus=@"finished";
        self.userID=@"";
        self.createrID=@"";
        self.isSelect=YES;
        [self addHeader];
        [self addFooter];
    }];

    DTKDropdownItem *item5=[DTKDropdownItem itemWithTitle:@"创建的任务" callBack:^(NSUInteger index, id info) {
        self.createrID=@"-1";
        self.userID=@"";
        self.taskStatus=@"";
        self.isSelect=YES;
        [self addHeader];
        [self addFooter];
    }];

    DTKDropdownMenuView *menuView=[DTKDropdownMenuView dropdownMenuViewForNavbarTitleViewWithFrame:CGRectMake(0,0,APPW/2,44) dropdownItems:@[item1,item2,item3,item4,item5]];
    menuView.currentNav=self.navigationController;
    menuView.dropWidth=150;
    menuView.titleFont=Font_Number(18);
    menuView.textColor=BlackColor;
    menuView.textFont=Font_Number(16);
    menuView.animationDuration=.3;
    menuView.selectedIndex=0;
    self.navigationItem.titleView=menuView;
}

// tableView
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,64,APPW,APPH-64) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=BGColor;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self.tableView registerClass:[TaskListTableViewCell class] forCellReuseIdentifier:TaskListTableViewCellIdentifier];
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.taskListArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TaskListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:TaskListTableViewCellIdentifier];
    cell.delegate=self;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.model=self.taskListArr[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kmargin*11;
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView=[UIView new];
    return footView;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return kmargin*4;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    TaskDetailViewController *vc=[TaskDetailViewController new];
    TaskListModel *model=self.taskListArr[indexPath.row];
    vc.model=model;
    [self.navigationController pushViewController:vc animated:NO];
}

@end
